package com.example.lib_common.view.view

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import com.example.lib_base.view.BaseActivity
import com.example.lib_common.view.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMvvmActivity<VDB:ViewDataBinding>:BaseActivity<VDB>(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //获取数据
        loadData()
        //订阅数据
        observeDataChang()
        //EventBus事件总线
        EventBus.getDefault().register(this)
    }

    //接收事件
@Subscribe(threadMode = ThreadMode.MAIN)

    public fun onReceiveEvent(event: CustomEvent?) {
        if (event!=null && event.target==this.javaClass.simpleName){
            //处理业务
            handEvent(event)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    //系统提供API实现页面之间传值

    //获取的启动器
    private val resultLauncher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
        if (result.resultCode== RESULT_OK){
            result.data?.let { handActivityResult(it) }
        }
    }


    //启动下一个Activity并接收返回结果
    protected open fun startNextActivityForResult(intent: Intent?){
//        intent?.run {
//            //相当于startActivity(this)
//
//        }
        resultLauncher.launch(intent)
    }



    //////子类获取页面返回的Intent对象，并从中获取数据
    protected open fun handActivityResult(data: Intent){

    }




    protected open fun startNextActivity(intent: Intent?){
        intent?.run {
            startActivity(this)
        }
    }

    protected open fun startNextActivityForResult(intent: Intent?,requestCode:Int){
        intent?.run {
            startActivityForResult(this,requestCode)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        receiveNextForResult(requestCode, resultCode, data)
    }
    protected open fun receiveNextForResult(requestCode: Int, resultCode: Int, data: Intent?){

    }



    //可以根据业务需要重写方法
    protected open fun loadData() {

    }
    //可以根据业务需要重写方法
    protected open fun observeDataChang() {

    }
    //交给子类处理事件
    protected open fun handEvent(event: CustomEvent){

    }
}